package com.peak.distribution.web;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.botaruibo.xvcode.generator.Generator;
import com.github.botaruibo.xvcode.generator.PngVCGenerator;
import com.peak.spring.boot.core.exception.Exceptions;
import com.peak.spring.boot.tools.DatePattern;
import com.peak.spring.boot.tools.Dates;
import com.peak.spring.boot.tools.Servlets;

import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/captcha")
@Slf4j
public class CaptchaController {

	@GetMapping("/get/{name}")
	public void getCaptcha(HttpServletRequest request, HttpServletResponse response, @PathVariable String name) {
		log.info("============请求验证码" + Servlets.getIp(request));
		// 设置相应类型,告诉浏览器输出的内容为图片
		response.setContentType("image/gif");
		// 不缓存此内容
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		try {
			Generator generator = new PngVCGenerator(120, 40, 4);
			BufferedImage image = generator.getValidCodeImage();
			// 保证是我们自己定义的验证码名称
			String code = CaptchaName.valueOf(name).name();
			request.getSession().setAttribute(code, generator.text());
			request.getSession().setAttribute(code + "_time", Dates.format(Dates.now(), DatePattern.NO_LINE_DATE_TIME));
			log.info("============请求验证码为：{}={}", code, generator.text());
			// 将内存中的图片通过流动形式输出到客户端
			ImageIO.write(image, "gif", response.getOutputStream());
		} catch (Exception e) {
			throw Exceptions.unchecked(e);
		}
	}

	public enum CaptchaName {
		agent_regist_code, user_forgot_code
	}
}
